package pers.cj.pdos.controller.file.img;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import pers.cj.pdos.utils.FileProperUtil;
import pers.cj.pdos.utils.FileUtils;
import pers.cj.pdos.utils.Utils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("/img")
public class ImageController {

    /**
     * 获取图片
     * @param path - 图片子路径
     * @param imgName - 图片名称
     * @param response
     * @throws IOException
     */
    @RequestMapping("/{path}/{imgName:.+}")
    public void user(@PathVariable("path")String path, @PathVariable("imgName")String imgName, HttpServletResponse response) throws IOException {
        if(Utils.isEmpty(path)) {
            response.getWriter().println("图片子路径不能为空");
            return;
        }

        if (imgName == null && imgName.equals("")){
            response.getWriter().println("图片名不能为空");
            return;
        }
        try {
            // img为图片的二进制流
            String filename = FileProperUtil.getInstance().getVal("image." + path) + imgName;
            byte[] img = FileUtils.read(filename);
            responseImg(img, response);
        } catch (IOException exception) {
            response.getWriter().println("未找到图片");
        }
    }

    private void responseImg(byte[] img, HttpServletResponse response) throws IOException {
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        os.write(img);
        os.flush();
        os.close();
    }
}
